<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{id?'编辑':'创建'}}文章</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-form label-position="right" label-width="100px">
        <el-form-item label="文章标题">
          <el-input style="width:250px" v-model="model.title"></el-input>
        </el-form-item>
        <el-form-item label="所属分类">
          <el-select v-model="model.categories" placeholder multiple>
            <el-option
              v-for="item in optionsData"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容">
          <vue-editor v-model="model.body" @image-added="handleImageAdded" useCustomImageHandler></vue-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="saveArticle">确定</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { VueEditor } from 'vue2-editor'
export default {
  name: 'EquipCreate',
  props: ['id'],
  components: { VueEditor },
  data() {
    return {
      model: {},
      optionsData: {}
    }
  },
  methods: {
    //获取分类数据
    async getOptionsData() {
      const res = await this.$http.get(`rest/categories`)
      this.optionsData = res.data.filter(item => {
        if (!item.categories || item.categories.name !== '新闻分类') {
          return false
        } else {
          return true
        }
      })
      console.log(res)
    },
    // 获取单条数据
    async getOneArticleData() {
      const res = await this.$http.get(`rest/articles/${this.id}`)
      this.model = res.data
      console.log(res.data)
    },
    async handleImageAdded(file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData()
      formData.append('file', file)
      const res = await this.$http.post(`upload`, formData)
      Editor.insertEmbed(cursorLocation, 'image', res.data.url) //存入这个编译器中
      resetUploader()
    },
    async saveArticle() {
      console.log(this.id)
      if (this.id) {
        await this.$http.put(`rest/articles/${this.id}`, this.model)
        this.$message.success('成功更新文章:${this.model.title}')
        this.$router.push('/articles/list')
      } else {
        await this.$http.post(`rest/articles`, this.model)
        this.$message.success('成功创建文章:${this.model.title}')
        this.$router.push('/articles/list')
      }
    }
  },
  created() {
    this.id && this.getOneArticleData()
    this.getOptionsData()
  }
}
</script>
<style>
</style>